<template>
  <view class="normal-login-container">
    <u-status-bar></u-status-bar>
    <!-- 背景图 -->
    <image src="/static/bj.png" class="w-750 h100vh fixed" style="top: 0;left: 0;" mode="aspectFill">
    </image>
    <!-- 表单 -->
    <view class="pl-32 pr-32 br-20 login_form bgff pt-30 pb-30">
      <view class="h-100 fs-36 title">食用林产品质量安全监管</view>
      <view class="h-100 fs-36 relative rowsc rowsm">
        <image src="/static/ren.png" class="w-40 h-40 input_icon" mode="aspectFil"></image>
        <input type="text" name="" id="" placeholder="请输入账号" class="user_name" v-model="loginForm.username">
      </view>
      <view class="h-100 fs-36 relative rowsc rowsm mb-20">
        <image src="/static/dlsuo.png" class="w-40 h-40 input_icon" mode="aspectFil"></image>
        <input type="password" name="" id="" placeholder="请输入密码" class="user_password" v-model="loginForm.password">
      </view>
      <view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
        <view class="login-code">
          <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
        </view>
      </view>
      <view class="h-100 fs-36 relative rows rowsm">
        <u-checkbox-group v-model="rememberGroup">
          <u-checkbox name="remember" shape="square" label="记住账号" activeColor="#50B439"></u-checkbox>
        </u-checkbox-group>
      </view>
      <view class="h-100 fs-36 relative rowsc rowsm">
        <view class="login_btn" @click="handleLogin">登录</view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCodeImg } from '@/api/login'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      codeUrl: "",
      captchaEnabled: true,
      // 用户注册开关
      register: false,
      globalConfig: getApp().globalData.config,
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: ""
      },
      rememberGroup: []
    }
  },
  created() {
    this.getCode()
  },
  onLoad(e) {
    this.opt = e
    // 如果本地有记住的用户名，则回填并默认勾选
    const savedUser = uni.getStorageSync('rememberedUsername')
    const savedPassword = uni.getStorageSync('rememberedPassword')
    if (savedUser) {
      this.loginForm.username = savedUser
      this.rememberGroup = ['remember']
    }
    if (savedPassword) {
      this.loginForm.password = savedPassword
    }
    // 检查是否已登录，如果已登录则跳转到首页
    // if (getToken()) {
    //   // 延迟跳转，确保页面完全加载
    //   setTimeout(() => {
    //     uni.reLaunch({ url: '/pages/index/index' })
    //   }, 100)
    // }
  },
  methods: {
    // 用户注册1
    handleUserRegister() {
      this.$tab.redirectTo(`/pages/register`)
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0]
      this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 用户协议
    handleUserAgrement() {
      let site = this.globalConfig.appInfo.agreements[1]
      this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 获取图形验证码
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    // 登录方法
    async handleLogin() {
      if (this.loginForm.username === "") {
        this.$modal.msgError("请输入账号")
      } else if (this.loginForm.password === "") {
        this.$modal.msgError("请输入密码")
      } else if (this.loginForm.code === "" && this.captchaEnabled) {
        this.$modal.msgError("请输入验证码")
      } else {
        this.$modal.loading("登录中，请耐心等待...")
        this.pwdLogin()
      }
    },
    // 密码登录
    async pwdLogin() {
      this.$store.dispatch('Login', this.loginForm).then((res) => {
        console.log('登录成功，返回数据:', res)
        // 记住账号
        if (this.rememberGroup.includes('remember')) {
          uni.setStorageSync('rememberedUsername', this.loginForm.username)
          uni.setStorageSync('rememberedPassword', this.loginForm.password)
        } else {
          uni.removeStorageSync('rememberedUsername')
          uni.removeStorageSync('rememberedPassword')
        }
        uni.hideLoading()
        this.$modal.closeLoading()
        this.loginSuccess()
      }).catch((error) => {
        console.log('登录失败，错误信息:', error)
        if (this.captchaEnabled) {
          this.getCode()
        }
      })
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
      // 设置用户信息
      this.$store.dispatch('GetInfo').then(res => {
        console.log('获取用户信息成功，返回数据:', res)
        uni.setStorageSync('userType', res.user.userType)
        this.$tab.reLaunch('/pages/workbench/workbench')
      }).catch(error => {
        console.log('获取用户信息失败，错误信息:', error)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
}
.login_form {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.title {
  font-family: SourceHanSansCN;
  font-weight: 400;
  font-size: 38rpx;
  color: #128215;
  text-align: center;
}

.input_icon {
  position: absolute;
  left: 20rpx;
  top: 50%;
  transform: translateY(-50%);
}

.user_name,
.user_password {
  width: 459rpx;
  height: 73rpx;
  background: #FFFFFF;
  border-radius: 16rpx;
  border: 1px solid #50B439;
  padding-left: 80rpx;
  background: linear-gradient(90deg, #F5FBF3 0%, #CCEBC5 100%);
}

.login_btn {
  width: 460rpx;
  height: 72rpx;
  font-family: SourceHanSansCN;
  font-size: 41rpx;
  color: #FFFFFF;
  background: #50B439;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-item {
  margin: 40px auto;
  background-color: #f5f6f7;
  height: 30px;
  border-radius: 20px;

  .icon {
    font-size: 38rpx;
    margin-left: 10px;
    color: #999;
  }

  .input {
    width: 100%;
    font-size: 14px;
    line-height: 20px;
    text-align: left;
    padding-left: 15px;
  }

}

.login-code {
  height: 30px;
  float: right;

  .login-code-img {
    height: 30px;
    position: absolute;
    margin-left: 10px;
    width: 160rpx;
  }
}
</style>
